import React, {useState,useEffect} from 'react';
import {Modal, TreeSelect,Skeleton} from "antd";
import ProForm, {ProFormText} from "@ant-design/pro-form";
import {showRole} from "@/services/role";

const Index = (props) => {

  const {isModalVisible,handleCancel,handleAdd,roleId,treeData}  = props
  // 角色的信息
  const [initialValues,setRoleData] = useState(null)

  // 默认选择的数据
  const [stateRole,setStateRole] =useState({value: []})

  useEffect(async ()=>{
    if (roleId !== null){
      const resluce = await showRole(roleId)

      const defaultData  =  resluce.data.permissions.data.map((item)=>{
        return item.id
      })
      const list = {
        value: defaultData
      }
      setStateRole(list)
      setRoleData(resluce.data)
    }
  },[])
  // 树状select配置
    const tProps = {
      treeData,
      showCheckedStrategy:TreeSelect.SHOW_PARENT,
      treeCheckable: true,
      value: stateRole.value,
      defaultValue: stateRole.value,
      onChange,
      placeholder: 'Please select',
      style: {
        width: '100%',
      },
    };
  // 选择之后的回调
  const onChange = value => {
    setStateRole({value})
  };
  return (
      <Modal title={roleId ? '编辑角色' : '添加角色'}
             visible={isModalVisible}
             onCancel={handleCancel}
             destroyOnClose={true}
             footer={false}>
        {
          initialValues == null && roleId !== null  ? <Skeleton active />
          :  <ProForm
          onFinish={async (value) => {handleAdd(value,stateRole,roleId)}}
          initialValues={initialValues}
          submitter={{
            searchConfig: {
              submitText: '提交',
            },
            submitButtonProps: {
              size: 'middle',
              style: {
                width: '100%',
              },
            },
          }}
          >
          <ProFormText
          name="name"
          label="用户名"
          placeholder="请输入用户名"
          rules={[
        {
          required: true,
          message: '请输入用户名',
        },
          ]}
          />
          <ProForm.Item
            rules={ roleId ? '' :[
              {
                required: true,
                message: '请选择',
              },
            ]}
            label='权限选择' name='permission_id'>
            <TreeSelect {...tProps} />
          </ProForm.Item>
          <ProFormText
          name="cn_name"
          label="昵称"
          placeholder="请输入昵称"
          rules={[
        {
          required: true,
          message: '昵称必填',
        },
          ]}
          />

          </ProForm>
        }
      </Modal>
  );
};

export default Index;
